import React, { useContext, useMemo, useRef, useState } from 'react';
import { AsyncTree, BaseHelp, BaseHelpProps, HelpContext, Panel, Table } from '../../functionalComponent';
import { borderStyle, compHoc, getGlobalConfig, IObject, Layout, iup, useApi, useRefCallback } from '../../util';
import { QueryPanel } from '../query-panel';
import { getHelpBeforeOpen } from './common';
const { Flex, Slider } = Layout;

const { Header, Footer, MultipleButtons } = BaseHelp;

const tableProps: any = {
  rowSelected: false,
  rowChecked: true,
  cache: false,
  headerMenu: false,
  style: { borderStyle: 'solid', borderColor: 'var(--border-color-split, #f0f0f0)', borderWidth: 1 }
};

/**
 * 树节点
 * @param onSelectedChange
 * @constructor
 */
interface Props {
  onSelectedChange: (keys: any, nodes: any) => void;
}

const FilterTree: React.FC<Props> = ({ onSelectedChange }) => {
  interface TreeResult {
    id: string;
    metricName: string;
    metricCode: string;
    children?: TreeResult[];
    currentLevel: any;
  }

  interface TreeNode {
    key: string;
    title: string;
    isLeaf?: boolean;
    children?: TreeNode[];
    isChecked?: boolean;
    currentLevel: any;
  }

  function convertTreeResultsToTreeNodes(treeResults: TreeResult[]): TreeNode[] {
    return treeResults.map(convertTreeResultToTreeNode);
  }

  function convertTreeResultToTreeNode(treeResult: TreeResult): TreeNode {
    const { id, metricName, children, currentLevel } = treeResult;

    const treeNode: TreeNode = {
      key: id,
      title: metricName,
      currentLevel: currentLevel
    };

    if (children && children.length > 0) {
      treeNode.children = convertTreeResultsToTreeNodes(children);
      treeNode.isLeaf = false;
    } else {
      treeNode.isLeaf = true;
    }

    return treeNode;
  }

  const treeRequest = useRefCallback(async () => {
    const curEnv = iup.getQueryValue('env') || 'prod';
    return iup.request
      .get({
        url: curEnv === 'dev' ? '/engine/metricTreeDesign/all' : '/engine/metricTree/all'
      })
      .then((res) => {
        const result = convertTreeResultsToTreeNodes(res.data);
        console.log('result, ', result);
        return result;
      });
  });

  return <AsyncTree request={treeRequest} onSelectedChange={onSelectedChange} virtual={true} />;
};
function HelpContent() {
  const {
    request,
    ok,
    contentParams: { getFieldValue, columns, helpTitle, helpId, selectedArray, multiple, footer },
    randomKey
  } = useContext<any>(HelpContext);
  const btnRef = useRef<any>();
  const formRef = useApi();
  const [activeKey, setActiveKey] = useState('0');
  const rightTable = useRef<any>();
  const getTable = () => iup.compIns[`${helpId}_${randomKey}_${activeKey}`].getApi();
  const getResult: any = () => {
    if (multiple) {
      const result = rightTable.current
        .getApi()
        .getRows()
        .map((r: any) => ({
          value: getFieldValue(r),
          label: getFieldValue(r, 'label'),
          origin: { ...r }
        }));
      return result.length > 0 ? result : undefined;
    } else {
      const value = getTable().getSelectedData()[0];
      if (value) {
        return { value: getFieldValue(value), label: getFieldValue(value, 'label'), origin: { ...value } };
      }
      return undefined;
    }
  };
  const toRight = (values: any) => {
    if (multiple) {
      btnRef.current.toRight(values);
    } else {
      ok(getResult());
    }
  };

  const onSelectCallback = useRefCallback((keys: any, nodes: any) => {
    getTable().setExtraParam({ treeNodes: nodes });
  });

  const queryItems = useMemo(
    () => [
      {
        name: 'metricName',
        label: '指标名称'
      }
    ],
    []
  );

  tableProps.checkbox = multiple ? 'checked' : false;
  tableProps.rowSelected = !multiple;
  tableProps.rowChecked = multiple;

  const renderTable = (index: number) => {
    return (
      <Table
        {...tableProps}
        style={{ ...tableProps.style }}
        id={`${helpId}_${randomKey}_${index}`}
        columns={columns}
        onRow={(rowIndex: any, table: { getRow: (arg0: any) => any }) => ({
          onDoubleClick: () => toRight([table.getRow(rowIndex)])
        })}
        autoLoad={false}
        request={request}
        pagination={{
          height: 32,
          showQuickJumper: false,
          align: 'left',
          targetContainer: multiple && index === 0 ? `${helpId}_${randomKey}_pagination` : ''
        }}
        response={(res: { total: any; list: any }) => ({ total: res.total ?? 0, record: res.list || [] })}
      />
    );
  };

  return (
    <Layout>
      <Header title={helpTitle || '指标帮助'} />
      <Flex direction="row" style={{ padding: '5px 5px 0 5px' }}>
        <Slider size={200} style={{ margin: '0 var(--inner-margin, 16px) 0 0' }}>
          <Panel
            title="指标分类树"
            autoFit
            style={{ ...borderStyle() }}
            bodyStyle={{ padding: 'var(--inner-padding, 8px)' }}
          >
            <FilterTree onSelectedChange={onSelectCallback} />
          </Panel>
        </Slider>
        <Flex direction="column">
          <QueryPanel items={queryItems} gridRef={`${helpId}_${randomKey}_0`} />
          <Flex direction="row" style={{ marginTop: -11 }}>
            <Layout.Flex style={{ paddingBottom: multiple ? 32 : 0 }}>{renderTable(0)}</Layout.Flex>
            {multiple && (
              <MultipleButtons
                getRowKey={getFieldValue}
                outRef={btnRef}
                getActiveTable={getTable}
                getResultTable={() => rightTable.current.getApi()}
              />
            )}
            {multiple && (
              <Layout.Flex style={{ paddingTop: 7, paddingBottom: activeKey === '0' ? 32 : 0 }}>
                <Table
                  {...tableProps}
                  columns={columns}
                  dataSource={selectedArray}
                  ref={rightTable}
                  onRow={(rowIndex: any) => ({
                    onDoubleClick: () => btnRef.current.toLeft(rowIndex)
                  })}
                />
                <div
                  id={`${helpId}_${randomKey}_pagination`}
                  style={{
                    position: 'absolute',
                    left: 221,
                    right: 5,
                    ...borderStyle(['left', 'right', 'bottom']),
                    paddingLeft: 10
                  }}
                />
              </Layout.Flex>
            )}
          </Flex>
        </Flex>
      </Flex>
      <Footer getResult={getResult}>{footer && <span style={{ flex: 1, width: 0 }} children={footer} />}</Footer>
    </Layout>
  );
}

interface metricsParamType {
  pageNum: number;
  pageSize: number;
  queryfilter?: {};
  metricTreeId?: number;
  metricName?: string;
  bizPrincipal?: string;
  clientSqlFilter?:
    | string
    | IObject
    | (({
        ds,
        row,
        value,
        dataIndex,
        helpId
      }: {
        ds: Array<any>;
        row: any;
        value: any;
        dataIndex: string;
        helpId: string;
      }) => string | IObject); // 查询参数
}

interface BaseMetricsHelp extends BaseHelpProps {
  /**
   * @description
   */
  displayField?: string;
  /**
   * @description       自定义弹出帮助的title
   */
  title?: string;
  /**
   * @description       是否开启多选模式
   * @default           false
   */
  multiple?: boolean;
  /**
   * @description       底部扩展组件
   */
  footer?: React.ReactNode;
  /**
   * @description       表格列配置
   */
  columns?: IObject[];
  /**
   * @description       物资列表参数
   */
  metricsParams?: metricsParamType;
  /**
   * @description       自定义指标请求
   */
  metricsRequest?: (params: metricsParamType | undefined) => Promise<{ list: any[]; total: number | string }>;
  /**
   * @description   查询参数
   */
  clientSqlFilter?:
    | string
    | IObject
    | (({
        ds,
        row,
        value,
        dataIndex
      }: {
        ds: Array<any>;
        row: any;
        value: any;
        dataIndex: string;
        helpId: string;
      }) => string | IObject);
}

export type IMetricsHelp = BaseMetricsHelp;

/**
 * 指标帮助
 */
export const MetricsHelp = compHoc<IMetricsHelp>((props) => {
  const cacheHelpInfo = useRef({ data: null, p: null });
  const {
    valueField = 'metricCode',
    labelField = 'metricName',
    displayField,
    userCodeField,
    clientSqlFilter,
    title,
    multiple = false,
    modalProps,
    footer,
    metricsRequest,
    metricsParams = {},
    columns,
    onBeforeOpen,
    ...others
  } = props;
  const otherProps: any = others;

  const curEnv = iup.getQueryValue('env') || 'prod';
  otherProps.onBeforeOpen = useRefCallback(async () => {
    const [status, helpInfo] = await getHelpBeforeOpen({ onBeforeOpen, cacheHelpInfo });
    if (iup.isObject(helpInfo)) {
      return helpInfo;
    }
    return status;
  });

  otherProps.request = useRefCallback(async ({ pageIndex, pageSize, params, treeNodes, ...queryFilter }: any) => {
    if (treeNodes && treeNodes.length > 0) {
      queryFilter['metricTreeId'] = treeNodes[0].key;
    }
    const data: IMetricsHelp['metricsParams'] = {
      ...params,
      pageNum: pageIndex,
      pageSize,
      metricStatus: 1,
      ...queryFilter
    };
    console.log(data);

    if (metricsRequest) {
      return await metricsRequest(data);
    }

    return iup.request
      .body({
        url: curEnv === 'dev' ? '/engine/metricDefDesign/pageMetricDef' : '/engine/metricDef/pageMetricDef',
        data
      })
      .then((res) => {
        if (res?.code === 0) {
          return res?.data;
        } else {
          return { list: [], total: 0 };
        }
      });
  });
  otherProps.valueField = valueField;
  otherProps.userCodeField = userCodeField;
  otherProps.labelField = labelField || displayField;
  // 自定义modal弹出窗需要使用的参数
  otherProps.contentParams = {
    footer,
    multiple,
    valueField,
    labelField: otherProps.labelField,
    columns: columns ?? [
      { dataIndex: 'metricName', title: '指标名称' },
      { dataIndex: 'metricCode', title: '指标编码' },
      {
        dataIndex: 'bizMetricType',
        title: '指标类型',
        tooltip: true,
        render: ({ row }) => {
          const value = row.bizMetricType;
          if (value === '1' || value === 1) {
            return '原子指标';
          } else if (value === '2' || value === 2) {
            return '派生指标';
          } else if (value === '3' || value === 3) {
            return '复合指标';
          } else {
            return '';
          }
        }
      },
      {
        dataIndex: 'mgrIsCore',
        title: '核心指标',
        tooltip: true,
        render: ({ row }) => {
          const value = row.mgrIsCore;
          if (value) {
            return '是';
          } else {
            return '否';
          }
        }
      }
    ]
  };
  if (title) {
    otherProps.contentParams.helpTitle = title;
  }
  const { width, height } = getGlobalConfig().default.helpConfig;
  return (
    <BaseHelp
      {...otherProps}
      modal
      helpContent={HelpContent}
      multiple={multiple}
      modalProps={{ width, height, ...modalProps }}
    />
  );
}, 'MetricsHelp');
export default MetricsHelp;
